package com.aztec.ims.service.dao;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Order;

import com.aztec.ims.domain.CarrierInformation;
import com.aztec.ims.service.om.Carriers;
import com.aztec.ims.service.response.GenericResponse;
import com.aztec.ims.service.util.HibernateUtil;

public class CarrierDetailsDao {
	public GenericResponse createCarrierDetails(
			CarrierInformation request) {
		Carriers om = convertRequestToOm(request);

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
    	session.save(om);
		session.getTransaction().commit();
		
		GenericResponse response = new GenericResponse(om.getCarrierId().toString());
		return response;
	}

	public List<CarrierInformation> getCarrierDetails() {

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
    	Criteria criteria = session.createCriteria(Carriers.class);
    	criteria.addOrder(Order.asc("carrierId"));
    	List results = criteria.list();
		session.getTransaction().commit();
		
		return convertOmToResponse(results);
		
	}

	private List<CarrierInformation> convertOmToResponse(List results) {
		List <CarrierInformation> response = new ArrayList<CarrierInformation>();
		
		if(results != null){
			for(Iterator iter = results.iterator();iter.hasNext();){
				Carriers om = (Carriers)iter.next();
				CarrierInformation carrierInfo = new CarrierInformation(om
						.getCarrierName(), om.getCarrierId().toString());
				response.add(carrierInfo);
			}
		}
		
		return response;
	}

	private Carriers convertRequestToOm(
			CarrierInformation request) {

		Carriers om = new Carriers();
		om.setCarrierName(request.getCarrierName());
		return om;
	}

}
